﻿using Microsoft.EntityFrameworkCore;
using OnlineStore.Models;

namespace OnlineStore.Data
{
    public class OnlineStoreDbContext : DbContext
    {
        public OnlineStoreDbContext(DbContextOptions<OnlineStoreDbContext> options) :
            base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Admin> Admins { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderDetail> OrderDetails { get; set; }
        public DbSet<Cart> Carts { get; set; }
        public DbSet<ContactInfo> ContactInfos { get; set; }
        public DbSet<ProductComment> ProductComments { get; set; }
        public DbSet<ProductImage> ProductImages { get; set; }
        public DbSet<ProductInCart> ProductInCarts { get; set; }
        public DbSet<ProductInOrder> ProductInOrders { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>()
                .HasIndex(user => user.Email)
                .IsUnique();

            modelBuilder.Entity<Order>()
                .HasIndex(order => order.Uid);


            #region 配置Order和OrderDetail

            // 配置Order和OrderDetail
            modelBuilder.Entity<Order>()
                .HasOne(o => o.OrderDetail)
                .WithOne(d => d.Order)
                .HasForeignKey<OrderDetail>(d => d.OrderId)
                .OnDelete(DeleteBehavior.NoAction);

            // 配置Order和ContactInfo
            modelBuilder.Entity<Order>()
                .HasOne(o => o.ContactInfo)
                .WithMany()
                .OnDelete(DeleteBehavior.NoAction);


            // 配置OrderDetail和ContactInfo
            modelBuilder.Entity<OrderDetail>()
                .HasOne(o => o.ContactInfo)
                .WithMany()
                .OnDelete(DeleteBehavior.NoAction);

            #endregion
        }
    }
}